package com.fqgj.xjd.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApiErrorException;
import com.fqgj.exception.enums.BasicErrorCodeEnum;
import com.fqgj.xjd.user.client.UserDeviceService;
import com.fqgj.xjd.user.client.enums.PlatformEnum;
import com.fqgj.xjd.user.client.request.ShumeiDevice;
import com.fqgj.xjd.user.client.request.ShumeiPageQueryRO;
import com.fqgj.xjd.user.client.request.TongDunDevice;
import com.fqgj.xjd.user.client.request.UserDevice;
import com.fqgj.xjd.user.common.enums.UserErrorCodeEnum;
import com.fqgj.xjd.user.config.ConfigUtil;
import com.fqgj.xjd.user.dao.UserBehaviorDeviceDao;
import com.fqgj.xjd.user.dao.UserBehaviorDeviceShumeiDao;
import com.fqgj.xjd.user.dao.UserBehaviorDeviceTongdunDao;
import com.fqgj.xjd.user.entity.UserBehaviorDeviceEntity;
import com.fqgj.xjd.user.entity.UserBehaviorDeviceShumeiEntity;
import com.fqgj.xjd.user.entity.UserBehaviorDeviceTongdunEntity;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName:
 * @Description: 用户设备信息服务
 * @Author zhangxingyun
 * @Create 2017-07-21 09:37
 */
@Service("userDeviceService")
public class UserDeviceServiceImpl implements UserDeviceService {

    public static final Logger LOGGER = LoggerFactory.getLogger(UserDeviceServiceImpl.class);
    @Autowired
    private UserBehaviorDeviceShumeiDao userBehaviorDeviceShumeiDao;

    @Autowired
    private UserBehaviorDeviceDao userBehaviorDeviceDao;

    @Autowired
    private UserBehaviorDeviceTongdunDao userBehaviorDeviceTongdunDao;

    @Autowired
    private OSSService ossService;

    @Autowired
    private ConfigUtil configUtil;

    /**
     * 添加数美的设备信息
     *
     * @param userCode
     * @param shumeiDevice
     * @return
     */
    @Override
    public Response<Boolean> addShumeiInfo(String userCode, ShumeiDevice shumeiDevice) {
        if (shumeiDevice == null) {
            return Response.error(UserErrorCodeEnum.PARAM_ERROR);
        }
        UserBehaviorDeviceShumeiEntity oldEntity = userBehaviorDeviceShumeiDao.selectByUserCode(userCode);
        if (oldEntity != null) {
            oldEntity.setDeleted(true);
            userBehaviorDeviceShumeiDao.updateByPrimaryKey(oldEntity);
        }
        UserBehaviorDeviceShumeiEntity entity = new UserBehaviorDeviceShumeiEntity();
        /**
         * 增加fingerprint_info_url字段
         */

        entity.setFingerprintInfoUrl(shumeiDevice.getFingerprintInfo());

        entity.setUserCode(userCode);
        entity.setSmid(shumeiDevice.getSmId());
        entity.setPlatform(shumeiDevice.getPlatformEnum().getType());
        userBehaviorDeviceShumeiDao.insert(entity);
        return Response.ok().putData(true);
    }

    /**
     * @param userCode
     * @return
     */
    @Override
    public Response<ShumeiDevice> getShumeiDeviceByUserCode(String userCode) {
        UserBehaviorDeviceShumeiEntity entity = userBehaviorDeviceShumeiDao.selectByUserCode(userCode);
//        StringBuilder fingerprintInfo = new StringBuilder();
//
//        if (null != entity.getFingerprintInfo()) {
//            fingerprintInfo.append(entity.getFingerprintInfo());
//        } else {
//            String fileUrl = entity.getFingerprintInfoUrl();
//            fileUrl = fileUrl.replace(configUtil.getQsyqBaseUrl(), "");
//            fingerprintInfo.append(ossService.getFileContent(configUtil.getBucketName(), fileUrl));
//        }
        if (null == entity) {
            return Response.error();
        }
        ShumeiDevice device = new ShumeiDevice(entity.getId(), entity.getSmid(), entity.getFingerprintInfoUrl(),
                PlatformEnum.getEnumByType(entity.getPlatform()), entity.getGmtCreate());
        return Response.ok().putData(device);
    }

    @Override
    public Response<List<ShumeiDevice>> getShuMeiDeviceListByPage(ShumeiPageQueryRO shumeiPageQueryRO) {
        if(shumeiPageQueryRO == null || shumeiPageQueryRO.getEndDate() == null){
            return Response.error(BasicErrorCodeEnum.PARAM_NOT_COMPLETE, "param can not be empty");
        }

        List<UserBehaviorDeviceShumeiEntity> userBehaviorDeviceShumeiEntities = userBehaviorDeviceShumeiDao.selectListByPage(shumeiPageQueryRO.getEndDate(), shumeiPageQueryRO.getPage());
        List<ShumeiDevice> shumeiDevices = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(userBehaviorDeviceShumeiEntities)){
            for(UserBehaviorDeviceShumeiEntity entity : userBehaviorDeviceShumeiEntities){
                ShumeiDevice device = new ShumeiDevice(entity.getId(), entity.getSmid(), entity.getFingerprintInfoUrl(),
                        PlatformEnum.getEnumByType(entity.getPlatform()), entity.getGmtCreate());
                shumeiDevices.add(device);
            }
        }
        return Response.ok().putData(shumeiDevices);
    }

    /**
     * @param userCode
     * @param userDevice
     * @return
     */
    @Override
    public Response<Boolean> addNewDevice(String userCode, UserDevice userDevice) {
        return Response.ok().putData(true);
    }

    /**
     * @param userDevice
     * @return
     */
    @Override
    public Response<Boolean> addNewDevice(UserDevice userDevice) {
        if (StringUtils.isEmpty(userDevice.getClientId())) {
            return Response.error();
        }
        UserBehaviorDeviceEntity entity = userBehaviorDeviceDao.selectDeviceByClientId(userDevice.getClientId());
        if (entity == null) {
            this.addDevice(userDevice);
        } else {
            if (StringUtils.isEmpty(userDevice.getUserCode())) {
                //userDevice.userCode 为空 则不作处理
                return Response.ok(true);
            }
            if (StringUtils.isEmpty(entity.getUserCode()) || userDevice.getUserCode().equals(entity.getUserCode())) {
                this.updateDevice(userDevice, entity);
            } else {
                this.addDevice(userDevice);
            }
        }
        return Response.ok().putData(true);
    }

    private void addDevice(UserDevice userDevice) {
        UserBehaviorDeviceEntity entity = new UserBehaviorDeviceEntity();
        if (StringUtils.isNotEmpty(userDevice.getGuestId())) {
            entity.setGuestId(userDevice.getGuestId());
        }
        if (StringUtils.isNotEmpty(userDevice.getClientId())) {
            entity.setClientId(userDevice.getClientId());
        }
        if (userDevice.getPlatform() != null) {
            entity.setPlatform(userDevice.getPlatform());
        }
        if (StringUtils.isNotEmpty(userDevice.getVersion())) {
            entity.setVersion(userDevice.getVersion());
        }
        if (StringUtils.isNotEmpty(userDevice.getVersionCode())) {
            entity.setVersionCode(userDevice.getVersionCode());
        }
        if (StringUtils.isNotEmpty(userDevice.getUserCode())) {
            entity.setUserCode(userDevice.getUserCode());
        }
        userBehaviorDeviceDao.insert(entity);
    }

    private void updateDevice(UserDevice userDevice, UserBehaviorDeviceEntity entity) {
        if (StringUtils.isNotEmpty(userDevice.getClientId())) {
            entity.setClientId(userDevice.getClientId());
        }
        if (userDevice.getPlatform() != null) {
            entity.setPlatform(userDevice.getPlatform());
        }
        if (StringUtils.isNotEmpty(userDevice.getVersion())) {
            entity.setVersion(userDevice.getVersion());
        }
        if (StringUtils.isNotEmpty(userDevice.getVersionCode())) {
            entity.setVersionCode(userDevice.getVersionCode());
        }
        if (StringUtils.isNotEmpty(userDevice.getUserCode())) {
            entity.setUserCode(userDevice.getUserCode());
        }
        userBehaviorDeviceDao.updateByPrimaryKey(entity);
    }

    /**
     * @param userCode
     * @return
     */
    @Override
    public Response<UserDevice> getUserDeviceListByUserCode(String userCode) {
        UserBehaviorDeviceEntity entity = userBehaviorDeviceDao.selectDeviceByUserCode(userCode);
        if (entity == null) {
            return Response.ok();
        }
        UserDevice userDevice = new UserDevice();
        userDevice.setGuestId(entity.getGuestId());
        return Response.ok().putData(userDevice);
    }

    /**
     * 根据用户ID和guestId获取设备
     *
     * @param userCode
     * @param guestId
     * @return
     */
    @Override
    public Response<UserDevice> getDeviceByUserCodeAndGuestId(String userCode, String guestId) {
        UserBehaviorDeviceEntity userDeviceEntity = userBehaviorDeviceDao.selectDeviceByUserCode(userCode);
        if (userDeviceEntity == null) {
            return Response.ok();
        }
        UserDevice userDevice = null;
        userDevice = new UserDevice();
        userDevice.setGuestId(userDeviceEntity.getGuestId());
        return Response.ok().putData(userDevice);
    }

    /**
     * 获取当前用户的最新的设备wifi map。结果为用户id和wifi名称的映射
     *
     * @param userCodes
     * @return
     */
    @Override
    public Response<Map<String, String>> getUserLatestWifiNameMapByUserCodes(List<String> userCodes) {
        List<UserBehaviorDeviceShumeiEntity> userShumeiDeviceInfoEntityList = userBehaviorDeviceShumeiDao.selectLatestByUserCodes(userCodes);
        if (CollectionUtils.isEmpty(userShumeiDeviceInfoEntityList)) {
            return Response.ok().putData(null);
        }

        Map<String, String> res = new ConcurrentHashMap<>();
        for (UserBehaviorDeviceShumeiEntity userShumeiDeviceInfoEntity : userShumeiDeviceInfoEntityList) {
            if (!res.containsKey(userShumeiDeviceInfoEntity.getUserCode())) {
                //从oss中获取字符串?单线程?
                StringBuilder fingerprintInfo = new StringBuilder();
                if (null == userShumeiDeviceInfoEntity.getFingerprintInfo()) {
                    String fileUrl = userShumeiDeviceInfoEntity.getFingerprintInfoUrl();
                    fileUrl = fileUrl.replace(configUtil.getQsyqBaseUrl(), "");
                    fingerprintInfo.append(ossService.getFileContent(configUtil.getBucketName(), fileUrl));
                } else {
                    fingerprintInfo.append(userShumeiDeviceInfoEntity.getFingerprintInfo());
                }
                //
                JSONObject jsonObject = JSON.parseObject(fingerprintInfo.toString());
                if (jsonObject == null) continue;
                String networkType = jsonObject.getString("networkType");
                if (StringUtils.isEmpty(networkType)) {
                    networkType = jsonObject.getString("network");
                }
                if (StringUtils.isNotEmpty(networkType) && networkType.equalsIgnoreCase("WIFI")) {
                    res.put(userShumeiDeviceInfoEntity.getUserCode(), jsonObject.getString("ssid"));
                }
            }
        }

        return Response.ok().putData(res);
    }

    @Override
    public Response<Boolean> addTongDunDeviceInfo(TongDunDevice tongDunDevice) {
        if (StringUtils.isEmpty(tongDunDevice.getUserCode())) {
            throw new ApiErrorException("userCode is empty");
        }

        if (StringUtils.isEmpty(tongDunDevice.getBlackbox())) {
            throw new ApiErrorException("blackbox is empty");
        }

        if (tongDunDevice.getPlatform() == null) {
            throw new ApiErrorException("platform is empty");
        }

        userBehaviorDeviceTongdunDao.deleteByUserCode(tongDunDevice.getUserCode());

        UserBehaviorDeviceTongdunEntity entity = new UserBehaviorDeviceTongdunEntity();
        entity.setUserCode(tongDunDevice.getUserCode());
        entity.setBlackbox(tongDunDevice.getBlackbox());
        entity.setPlatform(tongDunDevice.getPlatform());
        userBehaviorDeviceTongdunDao.insert(entity);

        return Response.ok().putData(true);
    }

    @Override
    public Response<TongDunDevice> getTongDunDeviceInfo(String userCode) {
        UserBehaviorDeviceTongdunEntity entity = userBehaviorDeviceTongdunDao.selectByUserCode(userCode);

        if (entity != null) {
            TongDunDevice tongDunDevice = new TongDunDevice();
            BeanUtils.copyProperties(entity, tongDunDevice);
            return Response.ok().putData(tongDunDevice);
        }

        return Response.ok().putData(null);
    }
}
